package com.example.calendertodo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.example.calendertodo.beam.Todo;
import com.example.calendertodo.util.ToastUtil;
import com.example.calendertodo.util.TodoDbOpenHelper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddActivity extends AppCompatActivity {
    private EditText et_title,et_context;
    private TextView tv_start,tv_end;
    private Button btn_add,btn_cancel;
    private ImageView iv_photo;
    private ImageButton ib_photo;
    private String startTime,endTime,Time,temp,temp1,temp_start,temp_start1,head,tail;
    private int flag,year,moon,day,hour,minute;
    private Uri imageUri;
    private TodoDbOpenHelper mTodoDbOpenHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_add);
        getCurrentTimeFormat();
        initView();
        mTodoDbOpenHelper = new TodoDbOpenHelper(this);



        //添加按钮事件
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String title = et_title.getText().toString();
                String content = et_context.getText().toString();
                String start_time = tv_start.getText().toString();
                String end_time = tv_end.getText().toString();
                String photo  = String.valueOf(imageUri);
                if (TextUtils.isEmpty(title)) {
                    ToastUtil.toastShort(AddActivity.this, "请编辑标题");
                    return;
                }
                if (TextUtils.isEmpty(start_time)) {
                    ToastUtil.toastShort(AddActivity.this, "请选择起始时间");
                    return;
                }
                if (TextUtils.isEmpty(end_time)) {
                    ToastUtil.toastShort(AddActivity.this, "请选择结束时间");
                    return;
                }
                if(start_time.compareTo(end_time) >= 0) {
                    ToastUtil.toastShort(AddActivity.this,"请选择正确的时间");
                    return;
                }
                Log.d("tag","------起始时间----" + startTime + "------结束时间----" + endTime + "---head--" + head);
                if(startTime.trim().compareTo(head) != 0 || endTime.trim().compareTo(head) != 0) {
                    ToastUtil.toastShort(AddActivity.this,"Todo时间应该设置在当天");
                    return;
                }


                Todo todo = new Todo();
                todo.setTitle(title);
                todo.setContent(content);
                todo.setStartTime(start_time);
                todo.setEndTime(end_time);
                todo.setState("0"); //添加事件时，给事件状态置为0
                todo.setPhoto(photo);
                long row  = mTodoDbOpenHelper.insertData(todo);//插入数据
                if(row != -1) {
                    ToastUtil.toastShort(AddActivity.this,"添加Todo成功");
                }else {
                    ToastUtil.toastShort(AddActivity.this,"添加失败");
                }
                Intent intent = new Intent(AddActivity.this, MainActivity.class);
                startActivity(intent);
                finish();

            }
        });


        //取消按钮事件
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tv_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new DatePickerDialog(AddActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {//年月日
                        int month = i1 + 1;// 此处i1从0开始，需要加一
                        if (month <= 9) {
                            temp_start = format(month);
                        }else {
                            temp_start = month + "";
                        }
                        if(i2 <= 9) {
                            temp_start1 = format(i2);
                        }else {
                            temp_start1 = i2 + "";
                        }
                        startTime = i +"-"  + temp_start + "-" + temp_start1 + "\t";
                        flag = 0;
                        Log.d("tag","------日期--------" + startTime);
                        popTimePick(startTime,flag);

                    }
                },year,moon,day).show();
            }
        });


        tv_end.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new DatePickerDialog(AddActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {//年月日
                        int month = i1 + 1;// 此处i1从0开始，需要加一
                        if (month <= 9) {
                            temp = format(month);
                        }else {
                            temp = month + "";
                        }
                        if(i2 <= 9) {
                            temp1 = format(i2);
                        }else {
                            temp1 = i2 + "";
                        }
                        endTime = i +"-"  + temp + "-" + temp1 + "\t";
                        flag = 1;
                        popTimePick(endTime,flag);
                    }
                },year,moon,day).show();
            }
        });

        ib_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(AddActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    takePhoto();
                } else {
                    ActivityCompat.requestPermissions(AddActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                }
            }
        });
    }

    private void initView() {
        et_title = findViewById(R.id.et_title);
        et_context = findViewById(R.id.et_context);
        btn_add = findViewById(R.id.btn_add);
        btn_cancel = findViewById(R.id.btn_cancel);
        tv_start = findViewById(R.id.tv_start);
        tv_end = findViewById(R.id.tv_end);
        iv_photo = findViewById(R.id.iv_photo);
        ib_photo = findViewById(R.id.ib_photo);
    }

    //选择具体时间
    public void popTimePick(String time,int flag) {
        new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int i, int i1) {
                String hour = "",minute = "";

                if(i <= 9) {
                    hour = format(i);
                }else {
                    hour = i + "";
                }

                if(i1 <= 9) {
                    minute = format(i1);
                }else {
                    minute = i1 + "";
                }
                Time = time + hour + ":" + minute;


                if (flag == 0) { //起始时间
                    tv_start.setText(Time);
                }else if(flag == 1) {
                    tv_end.setText(Time);
                }

            }
        },hour,minute,true).show();
    }


    private String format(int date) {
        String exact_date = "0" + date;
        return exact_date;
    }

    private void getCurrentTimeFormat() { //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd\tHH:mm");
        Date date = new Date();
        String time = simpleDateFormat.format(date);
        String[] times = time.split("\t");
        head = times[0];
        tail = times[1];
        year = Integer.parseInt(head.split("-")[0]);
        moon = Integer.parseInt(head.split("-")[1]) - 1;
        day = Integer.parseInt(head.split("-")[2]);
        hour = Integer.parseInt(tail.split(":")[0]);
        minute = Integer.parseInt(tail.split(":")[1]);
    }




    //获取照片资源请求

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePhoto();
            } else {
               ToastUtil.toastShort(this,"未获得权限");
            }
        }
    }


    private void takePhoto() {
        String filename = String.valueOf(new Date().getTime());
        File imageTemp = new File(getExternalCacheDir(), filename);
        try {
            imageTemp.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT > 24) {
            imageUri = FileProvider.getUriForFile(this, "com.example.calendertodo.fileprovider", imageTemp);
        } else {
            imageUri = Uri.fromFile(imageTemp);
        }
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            try {
                InputStream inputStream = getContentResolver().openInputStream(imageUri);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                iv_photo.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();

            }
        }
    }
}